package com.xxy.book.controller.component;

import cn.hutool.core.util.StrUtil;
import com.xxy.book.constant.CacheName;
import com.xxy.book.dto.UserDetailDTO;
import com.xxy.book.properties.JwtProperties;
import com.xxy.book.provider.JwtProvider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import com.xxy.book.cache.Cache;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;


import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author Xu XianYun
 * @Date 2023-01-09
 * @Description
 */
@Slf4j
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private JwtProvider jwtProvider;

    @Autowired
    private Cache caffeineCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        log.info("JWT过滤器通过校验请求头token进行自动登录...");

        //从请求头中拿到token信息
        String authToken = jwtProvider.getToken(request);
        //判断内容是否为空
        if (StrUtil.isNotEmpty(authToken) && authToken.startsWith(jwtProperties.getTokenPrefix())) {
            //去掉 "Bearer "前缀， 拿到真实token
            authToken = authToken.substring(jwtProperties.getTokenPrefix().length());

            // 拿到 token 中登录用户名
            String loginUsername = jwtProvider.getSubjectFromToken(authToken);

            //如果 登录名不为空 并且 没有认证过
            if (StrUtil.isNotEmpty(loginUsername)
                    && SecurityContextHolder.getContext().getAuthentication() == null) {
                //缓存中查询用户，不需要重新登录
                UserDetails userDetailDTO = caffeineCache.get(CacheName.USER, loginUsername, UserDetailDTO.class);

                //拿到用户信息之后，验证用户信息和 token
                if (userDetailDTO != null && jwtProvider.validateToken(authToken, userDetailDTO)) {
                    //1. 如果验证成功，构造 Authentication 对象
                    UsernamePasswordAuthenticationToken authenticationToken =
                            new UsernamePasswordAuthenticationToken(userDetailDTO,
                                    userDetailDTO.getPassword(),
                                    userDetailDTO.getAuthorities());

                    //2. 将 Authentication 对象存入 SecurityContext 上下文
                    SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                }

                log.info("JWT过滤器通过校验请求头token自动登录成功, user : {}", userDetailDTO.getUsername());
            }

        }
        filterChain.doFilter(request, response);
    }
}
